package com.echo.im.repository.offline.support;

import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Redis 消息存储仓库，只管理离线消息的 msgId 列表。
 * @author echo
 */
@Slf4j
@Component
public class RedisOfflineStorage {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    public RedisOfflineStorage(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public List<String> getMessageIds(String redisKey, Long lastFetchedMessageId, int size) {
        Set<String> msgIds = redisTemplate.opsForZSet().rangeByScore(redisKey, Double.parseDouble(String.valueOf(lastFetchedMessageId)), Double.MAX_VALUE, 0, size);
        if (msgIds == null || msgIds.isEmpty()) {
            return Collections.emptyList();
        }
        return msgIds.stream().collect(Collectors.toList());
    }

    public void deleteMessageIds(String redisKey, Long lastFetchedMessageId) {
        redisTemplate.opsForZSet().removeRangeByScore(redisKey, 0, Double.parseDouble(String.valueOf(lastFetchedMessageId)));
    }

    public void addMessageId(String redisKey, Long msgId, long timeout, TimeUnit unit) {
        redisTemplate.opsForZSet().add(redisKey, msgId.toString(), Double.parseDouble(String.valueOf(msgId)));
        redisTemplate.expire(redisKey, timeout, unit);
    }

    /**
     * 必须先保存MySQL后删除Redis
     */
    @Async
    public void checkAndBackupMessageIds(String redisKey, Long userId, int maxMessages, int backupSize, MySQLOfflineStorage mysqlStorage) {
        Long listSize = redisTemplate.opsForZSet().size(redisKey);
        if (listSize != null && listSize > maxMessages) {
            Set<String> msgIdsToBackup = redisTemplate.opsForZSet().range(redisKey, 0, backupSize - 1);
            if (msgIdsToBackup != null && !msgIdsToBackup.isEmpty()) {
                List<String> backupMsgIds = msgIdsToBackup.stream().collect(Collectors.toList());

                // 将这些 msgIds 保存到 MySQL 中
                mysqlStorage.saveMessageIds(userId, backupMsgIds);

                // 删除 Redis 中的这些 msgIds
                redisTemplate.opsForZSet().removeRange(redisKey, 0, backupSize - 1);

                log.info("用户 {} 的离线消息列表已超出最大长度，已备份并删除最早的 {} 条消息ID", userId, backupSize);
            }
        }
    }

    public void deleteOldMessage(String redisKey, int num) {
        redisTemplate.opsForZSet().removeRange(redisKey, 0, num);
    }

    public Long getMessageCount(String key) {
        return redisTemplate.opsForZSet().size(key);
    }
}
